package com.ruoyi.evalution.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.evalution.mapper.LabEvalutionTargetMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.evalution.domain.LabEvalutionResult;
import com.ruoyi.evalution.domain.LabEvalutionTarget;
import com.ruoyi.evalution.dto.UserScoreDto;
import com.ruoyi.evalution.service.ILabEvalutionResultService;
import com.ruoyi.evalution.service.ILabEvalutionTargetService;
import com.ruoyi.labdata.domain.LabEmployee;
import com.ruoyi.labdata.domain.LabFile;
import com.ruoyi.labdata.service.ILabEmployeeService;
import com.ruoyi.labdata.service.ILabFileService;
import com.ruoyi.system.utils.FileTypeEnum;
import com.ruoyi.utils.LockUtil;

/**
 * 评试对象Service业务层处理
 * 
 * @author winner pan
 * @date 2022-04-15
 */
@Service
public class LabEvalutionTargetServiceImpl implements ILabEvalutionTargetService {
	@Autowired
	private LabEvalutionTargetMapper labEvalutionTargetMapper;
	@Autowired
	private LockUtil lockUtil;
	@Autowired
    private ILabFileService labFileService;
	@Autowired
	private ILabEvalutionResultService labEvalutionResultService;
	@Autowired
	private ILabEmployeeService labEmployeeService;
	
	private static final String belongType = FileTypeEnum.ReportFile.getValue();

	/**
	 * 查询评试对象
	 * 
	 * @param participatorId
	 *            评试对象ID
	 * @return 评试对象
	 */
	@Override
	public LabEvalutionTarget selectLabEvalutionTargetById(Long participatorId) {
		List<LabFile> labFiles = labFileService.getFiles(participatorId, belongType);
		LabEvalutionTarget target = labEvalutionTargetMapper.selectLabEvalutionTargetById(participatorId);
		target.setImages(labFiles);
		return target;
	}

	/**
	 * 查询评试对象列表
	 * 
	 * @param labEvalutionTarget
	 *            评试对象
	 * @return 评试对象
	 */
	@Override
	public List<LabEvalutionTarget> selectLabEvalutionTargetList(LabEvalutionTarget labEvalutionTarget) {
		return labEvalutionTargetMapper.selectLabEvalutionTargetList(labEvalutionTarget);
	}
	/**
	 * 获取某次测评的所有人员的分数
	 * 
	 * **/
	public List<UserScoreDto> exportLabEvalutionTargetList(Long instanceId) {
		LabEvalutionTarget labEvalutionTarget = new LabEvalutionTarget();
		labEvalutionTarget.setEvalutionId(instanceId);
		//labEvalutionTarget.setEvalutionId(evalutionId);
		List<LabEvalutionTarget> targetScoreList = labEvalutionTargetMapper.selectLabEvalutionTargetList(labEvalutionTarget);
		List<LabEmployee> userList = labEmployeeService.queryEmployeeSCore(instanceId);
		//String employeeId
		List<UserScoreDto> scoreList = new ArrayList<UserScoreDto>();
		Map<String, LabEmployee> userMap = new HashMap<String,LabEmployee>();
		userList.forEach(item ->{
			userMap.put(item.getUserName(), item);
		});
		targetScoreList.forEach(item ->{
			UserScoreDto  dto = new UserScoreDto();
			LabEmployee user = userMap.get(item.getUserName());
			if(user!=null){
				dto.setOrgName(user.getOrgName());
				dto.setSex(user.getSex().equals("0")?"男":"女");
				dto.setBirthday(user.getBirthday());
				dto.setDegree(user.getEducation());
				//dto.setLabType(labType);
				dto.setMobile(user.getPhonenumber());
				dto.setEmail(user.getEmail());
				dto.setTitle(user.getTitle());
			}
			dto.setUserName(item.getUserName());
			dto.setNickName(item.getNickName());
			if(item.getStudentScore()!=null){
				dto.setStudentScore(item.getStudentScore().toPlainString());
			}
			if(item.getLeaderScore()!=null){
				dto.setLeadScore(item.getLeaderScore().toPlainString());
			}
			if(item.getColleagueScore()!=null){
				dto.setColleageScore(item.getColleagueScore().toPlainString());
			}
			if(item.getTotalScore()!=null){
				dto.setAverageSCore(item.getTotalScore().toPlainString());
			}
			scoreList.add(dto);
		});
		return scoreList;
	}

	/**
	 * 新增评试对象
	 * 
	 * @param labEvalutionTarget
	 *            评试对象
	 * @return 结果
	 */
	@Override
	public int insertLabEvalutionTarget(LabEvalutionTarget labEvalutionTarget) {
		return labEvalutionTargetMapper.insertLabEvalutionTarget(labEvalutionTarget);
	}

	/**
	 * 修改评试对象
	 * 
	 * @param labEvalutionTarget
	 *            评试对象
	 * @return 结果
	 */
	@Override
	@Transactional
	public int updateLabEvalutionTarget(LabEvalutionTarget labEvalutionTarget) {
		List<LabFile> labFiles = labEvalutionTarget.getImages();
		labFileService.updateFiles(labFiles, labEvalutionTarget.getParticipatorId(), belongType);
		if(labFiles!=null && labFiles.size()>0){
			for(LabFile labFile : labFiles){
				if(labFile.getIsDelete()==null){
					labEvalutionTarget.setReportFileId(labFile.getFileId());
				}
			}
		}
		return labEvalutionTargetMapper.updateLabEvalutionTarget(labEvalutionTarget);
	}
	/***
	 * 给测评对象打分.
	 * @param labEvalutionTarget
	 * @return
	 */
	@Transactional
	public int scoreRecord(LabEvalutionTarget labEvalutionTarget) {
		String lockKey = "LabEvalutionTarget:"+labEvalutionTarget.getParticipatorId();
		boolean isLock = lockUtil.lock(lockKey, 60*1000);
		if(!isLock){
			throw new RuntimeException("系统正忙请稍后提交.");
		}
		try{
			LabEvalutionResult result = new LabEvalutionResult();
			result.setParticipatorId(labEvalutionTarget.getParticipatorId());
			result.setUserName(SecurityUtils.getUsername());
			List<LabEvalutionResult> resultList = this.labEvalutionResultService.selectLabEvalutionResultList(result);
			if(resultList.size()>0){
				result = resultList.get(0);	
			}
			result.setRecordType(labEvalutionTarget.getRelation());
			result.setScore(labEvalutionTarget.getTotalMarkScore());
			result.setCreateTime(new Date());
			result.setNickName(SecurityUtils.getNickName());
			result.setPoliticsScore(labEvalutionTarget.getPoliticsScore());
			result.setAttitudeScore(labEvalutionTarget.getAttitudeScore());
			result.setDutiesScore(labEvalutionTarget.getDutiesScore());
			if(result.getEvalutionResultId()!=null){
				this.labEvalutionResultService.updateLabEvalutionResult(result);
			}else{
				this.labEvalutionResultService.insertLabEvalutionResult(result);
			}
			LabEvalutionTarget targetScore = labEvalutionTargetMapper.selectLabEvalutionTargetById(labEvalutionTarget.getParticipatorId());
			BigDecimal avgScore = labEvalutionResultService.getParticipatorAvgScore(result);
			if(labEvalutionTarget.getRelation().equals("leader")){
				targetScore.setLeaderScore(avgScore);
			}else if(labEvalutionTarget.getRelation().equals("colleague")){
				targetScore.setColleagueScore(avgScore);
			}else if(labEvalutionTarget.getRelation().equals("student")){
				targetScore.setStudentScore(avgScore);
			}else{
				throw new RuntimeException("不能认识的评分关系："+labEvalutionTarget.getRelation()+"评分关系:{'leader','colleague','student'}");
			}
			BigDecimal studentScore = null;
			BigDecimal leadScore = null;
			BigDecimal colleageScore = null;
			if(targetScore.getColleagueScore()==null && 
					targetScore.getStudentScore()==null){
				targetScore.setTotalScore(targetScore.getLeaderScore());
			}else if(targetScore.getColleagueScore()==null && targetScore.getLeaderScore()==null){
				targetScore.setTotalScore(targetScore.getStudentScore());
			}else if(targetScore.getLeaderScore()==null && 
					targetScore.getStudentScore()==null){
				targetScore.setTotalScore(targetScore.getColleagueScore());
			}else if(targetScore.getColleagueScore()==null){
				studentScore = targetScore.getStudentScore().multiply(new BigDecimal("0.4"));
				leadScore = targetScore.getLeaderScore().multiply(new BigDecimal("0.6"));
				targetScore.setTotalScore(leadScore.add(studentScore));
			}else if(targetScore.getStudentScore()==null){
				colleageScore = targetScore.getColleagueScore().multiply(new BigDecimal("0.4"));
				leadScore = targetScore.getLeaderScore().multiply(new BigDecimal("0.6"));
				targetScore.setTotalScore(leadScore.add(colleageScore));
			}else if(targetScore.getLeaderScore()==null){
				colleageScore = targetScore.getColleagueScore().multiply(new BigDecimal("0.5"));
				studentScore = targetScore.getStudentScore().multiply(new BigDecimal("0.5"));
				targetScore.setTotalScore(studentScore.add(colleageScore));
			}else{
				leadScore = targetScore.getLeaderScore().multiply(new BigDecimal("0.4"));
				colleageScore = targetScore.getColleagueScore().multiply(new BigDecimal("0.3"));
				studentScore = targetScore.getStudentScore().multiply(new BigDecimal("0.3"));
				targetScore.setTotalScore(studentScore.add(colleageScore).add(leadScore));
			}
			return labEvalutionTargetMapper.updateLabEvalutionTarget(targetScore);
		}finally{
			lockUtil.unLock(lockKey);
		}
	}


	/**
	 * 删除评试对象信息
	 * 
	 * @param participatorId
	 *            评试对象ID
	 * @return 结果
	 */
	@Override
	@Transactional
	public int deleteLabEvalutionTargetById(Long participatorId) {
		labFileService.deleteLabFile(participatorId, belongType);
		return labEvalutionTargetMapper.deleteLabEvalutionTargetById(participatorId);
	}
	
	public int deleteLabEvalutionTargetByEvalution(Long evalutionId){
		return labEvalutionTargetMapper.deleteLabEvalutionTargetByEvalution(evalutionId);
	}

	@Override
	public List<LabEvalutionTarget> selectReportHisList(LabEvalutionTarget labEvalutionTarget) {
		return labEvalutionTargetMapper.selectReportHisList(labEvalutionTarget);
	}

	@Override
	public List<LabEvalutionTarget> selectMarkScoreList(LabEvalutionTarget labEvalutionTarget) {
		return labEvalutionTargetMapper.selectMarkScoreList(labEvalutionTarget);
	}

	@Override
	public LabEvalutionTarget selectLabEvalutionTargetScoreById(Long participatorId, String userName) {
		return labEvalutionTargetMapper.selectLabEvalutionTargetScoreById(participatorId, userName);
	}
	
	/*public static void main(String[] args){
		BigDecimal a = new BigDecimal("100");
		BigDecimal b = new BigDecimal("0.9");
		System.out.println(a.multiply(b));
	}*/
}
